package com.project.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 切面类
 */
@Component//声明该类为spring组件类
@Aspect //声明该类为切面类
public class ServiceAspect {
    @Before("execution(* com.project.service..*.*(..))")
    public void  beforeMethod(){
        System.out.println("前通知");
    }
//    @AfterReturning("execution(* com.project.service..*.*(..))")
    @After("execution(* com.project.service..*.*(..))")
    public void afterMethod(){
        System.out.println("打印后通知");
    }

    @Around("execution(* com.project.service..*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint jp){
        try {
            System.out.println("环绕前");
            //执行目标方法，得到方法执行后的返回值
          Object o =  jp.proceed();

//         Object ot =  jp.getTarget();//得到目标对象
            System.out.println("环绕后");

          return o;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    @AfterThrowing(value = "execution(* com.project.service..*.*(..))",throwing = "e")
    public void throwException(JoinPoint jp ,Exception e){
     Object o =  jp.getTarget();//得到目标对象
      String methodName =  jp.getSignature().getName();//得到目标方法的名称
        System.out.println(o.getClass().getName()+"的"+methodName+"()方法时，抛出"
        +e.getClass().getName());
    }
}
